package com.ccl.iot.privates;import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;

public class BitmapStorer {
	public final static CompressFormat KDEFAULT_COMPRESS_FORMAT = CompressFormat.JPEG;
	public final static int KDEFAULT_COMPRESS_QUALITY = 100;
	public final static String KDEFAULT_FILE_SUFFIX = ".jpg";
	
	/*
	 * 	Static functions
	 */
	public static boolean Save(Bitmap aBitmap, String aFile){
		if (aBitmap != null && aFile != null){
			try {
				new File(aFile).getParentFile().mkdirs();
				
				return aBitmap.compress(KDEFAULT_COMPRESS_FORMAT, KDEFAULT_COMPRESS_QUALITY, new FileOutputStream(aFile));
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
		}
		
		return false;
	}
	
	public static Bitmap Load(String aFile){
		if (aFile != null){
			FileInputStream tStream = null;
			Bitmap tBitmap = null;
			
			try {
				tStream = new FileInputStream(aFile);
				
				tBitmap = BitmapFactory.decodeStream(tStream);
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			if (tStream != null){
				try {
					tStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			
			return tBitmap;
		}
		
		return null;
	}
	
	/*
	 * 	Non-static functions
	 */
	private String iPath = null;
	
	public BitmapStorer(String aPath){
		iPath = aPath;
	}
	
	private String getFile(String aID){
		if (aID != null){
			return iPath + File.separator + aID;
		}else{
			return null;
		}
	}
	
	private String getFileName(String aID){
		if (aID != null){
			byte tIDs[] = aID.getBytes();
			
			if (tIDs != null && tIDs.length > 0){
				StringBuilder tID = new StringBuilder();
				
				for (int i = 0; i < tIDs.length; i++){
					tID.append(Integer.toString(tIDs[i], Character.MAX_RADIX));
				}
				
				return tID.toString() + KDEFAULT_FILE_SUFFIX;
			}
		}
		
		return null;
	}
	
	public boolean contains(String aID){
		if (aID != null){
			String tFileName = getFile(getFileName(aID));
			
			if (tFileName != null){
				return new File(tFileName).exists();
			}
		}
		
		return false;
	}
	
	public Bitmap get(String aID){
		if (aID != null){
			String tFileName = getFileName(aID);
			
			return Load(getFile(tFileName));
		}
		
		return null;
	}
	
	public boolean put(String aID, Bitmap aBitmap){
		if (aID != null && aBitmap != null){
			String tFileName = getFileName(aID);
			
			return Save(aBitmap, getFile(tFileName));
		}
		
		return false;
	}
	
	public boolean remove(String aID){
		if (aID != null){
			String tFileName = getFile(getFileName(aID));
			
			if (tFileName != null){
				File tFile = new File(tFileName);
				
				if (tFile.exists()){
					return tFile.delete();
				}
			}
		}
		
		return false;
	}
}
